package com.asia5b.a5mall.middleware.logic.viewmodel.shop

import androidx.lifecycle.MutableLiveData
import com.asia5b.a5mall.middleware.base.SimpleNetParams
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.model.home.CategoryModel
import com.asia5b.a5mall.middleware.model.shop.ApplyShopResModel
import com.asia5b.a5mall.middleware.utils.JsonUtil
import com.google.gson.reflect.TypeToken
import io.reactivex.functions.Consumer
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * Created by zhangyuncai on 2020/6/28.
 */
class ApplyShopActivityVM:SimpleViewModel() {

    fun getShopsApply() {
        val netParams = SimpleNetParams(isShowLoading = false)//该接口无返回Body，会报错，所以不吐司
        baseSubscribe(shopApi.getApplyShopState().flatMap { shopApi.getShopsApply() }, netParams, Consumer {
//            callback.accept(it)
            getShopsApplyLiveData.value=it
        })
    }
    val getShopsApplyLiveData= MutableLiveData<ApplyShopResModel>()
    val putShopsApplyLiveData= MutableLiveData<Array<Any>>()
    val loadLeftDatasLiveData= MutableLiveData<ArrayList<CategoryModel>>()
    val uploaderLiveData= MutableLiveData<String>()

    fun putShopsApply(step: String, applyShopResModel: ApplyShopResModel) {
        val json = JsonUtil.anyToJson(applyShopResModel)
        val type = object : TypeToken<HashMap<String, Any>>() {}.type
        val map = JsonUtil.jsonToAny<HashMap<String, Any>>(json, type)!!
        baseSubscribe(shopApi.putShopsApply(step, map).flatMap { shopApi.getShopsApply() }, Consumer {
            putShopsApplyLiveData.value= arrayOf(it,step)
        })
    }

    /**
     * @Note   加载分类数据
     */
    fun loadLeftDatas() {
        val observable = categoryApi.getParentCat()
        baseSubscribe(observable, Consumer {
            loadLeftDatasLiveData.value=it
        })
    }

    /**
     * 将图片资料上传至云服务器
     */
    fun uploader(filePath: String) {
        val localFile = File(filePath)
        val localRequestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), localFile)
        val localPart = MultipartBody.Part.createFormData("file", localFile.name, localRequestBody)
        val observable = baseApi.uploader(localPart, "")
                .map { uploadImgResModel ->
                    return@map uploadImgResModel.url
                }
        baseSubscribe(observable, Consumer {
            uploaderLiveData.value=it
        })
    }
}